package api

import (
	"fmt"
	"github.com/mozillazg/go-pinyin"
	"jgt-oper/src/bll"
	"jgt-oper/src/context"
	"jgt-oper/src/schema"
	"sort"
)

// ContactsBook 通讯录控制器
type ContactsBook struct {
	ContactsBookBll *bll.ContactsBook `inject:""`
	EnterpriseBll   *bll.Enterprise   `inject:""`
	UserBll         *bll.User         `inject:""`
}

// ArrayListUser 用户数组
type ArrayListUser struct {
	Tag  interface{}              `json:"tag" structs:"tag"`
	List []*schema.UserItemDetail `json:"list" structs:"list"`
}

// Get 查询通讯录
func (a *ContactsBook) Get(ctx *context.Context) error {
	ctx.WriteOperateLog("ContactsBook.Get", "移动端-通讯录-获取企业相关信息")

	var (
		itemUser       *schema.User
		itemEnterprise *schema.Enterprise
		err            error
	)
	itemUser, err = a.UserBll.Get(ctx.GetUserID())
	if err != nil {
		return ctx.ResErrInternalServer(err)
	} else if itemUser == nil {
		return ctx.ResErrBadRequest(fmt.Errorf("无效的用户"))
	}
	itemEnterprise, err = a.EnterpriseBll.Get(itemUser.EnterpriseID)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	} else if itemEnterprise == nil {
		return ctx.ResErrBadRequest(fmt.Errorf("未找到企业数据"))
	}
	var total int
	total, err = a.ContactsBookBll.GetTotal(itemEnterprise.RecordID)
	if err != nil {
		return ctx.ResErrBadRequest(fmt.Errorf("获取企业员工总数出错"))
	}
	data := map[string]interface{}{
		"name":      itemEnterprise.Name,
		"record_id": itemEnterprise.RecordID,
		"logo":      itemEnterprise.Logo,
		"total":     total,
	}
	return ctx.ResSuccess(data)
}

//GetAllColleagues 查询所有的同事
func (a *ContactsBook) GetAllColleagues(ctx *context.Context) error {
	ctx.WriteOperateLog("ContactsBook.GetAllColleagues", "移动端-通讯录-获取当前用户所在企业所有在职员工信息")
	pageIndex, pageSize := ctx.GetPageIndex(), ctx.GetPageSize()
	var (
		itemUser          *schema.User
		allFrequentlyUsed *schema.ContactsBook
		err               error
	)
	itemUser, err = a.UserBll.Get(ctx.GetUserID())
	if err != nil {
		return ctx.ResErrInternalServer(err)
	} else if itemUser == nil {
		return ctx.ResErrBadRequest(fmt.Errorf("无效的用户"))
	}
	//获取我的常用联系人
	allFrequentlyUsed, err = a.ContactsBookBll.GetMyFrequentlyUsed(ctx.GetUserID())
	if err != nil {
		return ctx.ResErrBadRequest(fmt.Errorf("获取当前用户的常用联系人列表错误"))
	}
	fmt.Println("我常用联系人:", allFrequentlyUsed)
	//获取本公司的所有在职员工信息
	var allColleaguesSlice []*schema.QueryResultColleagues
	allColleaguesSlice, err = a.ContactsBookBll.GetAllColleagues(itemUser.EnterpriseID, ctx.Query("name"))
	if err != nil {
		return ctx.ResErrBadRequest(fmt.Errorf("获取当前用户所在公司的员工列表错误"))
	}
	//标记处理 所有的用户 的拼音字段
	for _, everyItem := range allColleaguesSlice {
		if everyItem.RealName == "" {
			everyItem.Pinyin = "#"
			continue
		}
		for _, nameString := range pinyin.LazyConvert(everyItem.RealName, nil) {
			everyItem.Pinyin += nameString
		}
		fmt.Println(everyItem.Pinyin)
	}
	//	按照拼音字段进行排序
	sort.Sort(schema.QueryResultColleaguesSlice(allColleaguesSlice))
	for _, user := range allColleaguesSlice {
		fmt.Println("user:record_id-->", user)
	}
	//掐取 用户指定查询的用户信息（根据pageIndex,pageSize）
	currentPageItems := make([]*schema.QueryResultColleagues, 0)
	if int(pageIndex)+int(pageSize)-1 <= len(allColleaguesSlice) {
		if pageIndex == 1 {
			currentPageItems = allColleaguesSlice[:pageIndex+pageSize]
		} else {
			currentPageItems = allColleaguesSlice[int(pageIndex) : pageIndex+pageSize]
		}
	} else {
		if pageIndex == 1 {
			currentPageItems = allColleaguesSlice[:]
		} else {
			currentPageItems = allColleaguesSlice[int(pageIndex):]
		}
	}
	//	请求的用户的id数组
	allUserID := make([]string, 0)
	for _, value := range currentPageItems {
		allUserID = append(allUserID, value.RecordID)
	}

	//查询请求的指定用户 的信息
	var currentPageItemsDetail []*schema.UserItemDetail
	currentPageItemsDetail, err = a.ContactsBookBll.GetColleaguesDetail(allUserID)
	//处理标记用户信息的特定信息
	for _, everyItem := range currentPageItemsDetail {
		if everyItem.RealName == "" {
			everyItem.Tag = "#"
			everyItem.NamePinyin = "#"
			continue
		}
		//标记汉语拼音
		for _, nameString := range pinyin.LazyConvert(everyItem.RealName, nil) {
			everyItem.NamePinyin += nameString
		}
		//标记汉语拼音首字母（大写）
		name := everyItem.NamePinyin
		if len(name) == 0 {
			everyItem.Tag = "#"
		} else if []byte(name)[0] >= 65 && []byte(name)[0] <= 90 || []byte(name)[0] >= 97 && []byte(name)[0] <= 122 {
			fmt.Println([]byte(name))
			everyItem.Tag = string([]byte(name)[0] - 32)
		} else {
			everyItem.Tag = "#"
		}

		//标记是否是已经添加多常用联系人
		everyItem.Added = 0
		for _, usedUser := range allFrequentlyUsed.FrequentlyUsedList {
			fmt.Println("常用联系人:", usedUser)
			if everyItem.RecordID == usedUser {
				fmt.Println("已添加-->常用联系人:", usedUser)
				everyItem.Added = 1
				break
			}
		}
	}
	//按照汉语拼音（全拼）排序
	sort.Sort(schema.CurrentPageItems(currentPageItemsDetail))
	for _, value := range currentPageItemsDetail {
		fmt.Println("detail--->user:", value)
	}

	//	按照页面其要求的数据结构进行组装返回的数据
	resultArray := make([]*ArrayListUser, 0)
	if len(currentPageItemsDetail) == 0 {

	} else if len(currentPageItemsDetail) == 1 {
		itemMap := new(ArrayListUser)
		itemMap.Tag = currentPageItemsDetail[0].Tag
		itemMap.List = currentPageItemsDetail
		resultArray = append(resultArray, itemMap)
	} else {
		previousItem := new(ArrayListUser)
		previousItem.Tag = currentPageItemsDetail[0].Tag
		previousItem.List = make([]*schema.UserItemDetail, 0)
		previousItem.List = append(previousItem.List, currentPageItemsDetail[0])
		resultArray = append(resultArray, previousItem)
		for index := 1; index < len(currentPageItemsDetail); index++ {
			if currentPageItemsDetail[index].Tag == currentPageItemsDetail[index-1].Tag {
				previousItem.List = append(previousItem.List, currentPageItemsDetail[index])
			} else {
				previousItem = new(ArrayListUser)
				previousItem.Tag = currentPageItemsDetail[index].Tag
				previousItem.List = make([]*schema.UserItemDetail, 0)
				previousItem.List = append(previousItem.List, currentPageItemsDetail[index])
				resultArray = append(resultArray, previousItem)
			}
		}
	}
	fmt.Println(resultArray)

	return ctx.ResSuccess(resultArray)
}

// GetAllFrequentlyUsed 查询所有的常用联系人
func (a *ContactsBook) GetAllFrequentlyUsed(ctx *context.Context) error {
	ctx.WriteOperateLog("ContactsBook.GetAllFrequentlyUsed", "移动端-通讯录-获取当前用户的所有的常用联系人信息")
	pageIndex, pageSize := ctx.GetPageIndex(), ctx.GetPageSize()

	var allFrequentlyUsed *schema.ContactsBook
	var err error

	allFrequentlyUsed, err = a.ContactsBookBll.GetMyFrequentlyUsed(ctx.GetUserID())
	if err != nil {
		return ctx.ResErrBadRequest(fmt.Errorf("获取当前用户的常用联系人列表错误"))
	}
	//	查询所有的常用联系人信息详情
	listRecordID := make([]string, 0)
	for _, recordID := range allFrequentlyUsed.FrequentlyUsedList {
		listRecordID = append(listRecordID, recordID)
	}
	var allFrequently []*schema.UserItemDetail
	allFrequently, err = a.ContactsBookBll.GetColleaguesDetail(listRecordID)
	if err != nil {
		return ctx.ResErrBadRequest(fmt.Errorf("获取当前用户所在公司的员工列表错误"))
	}
	//	按照页面要求，格式化数据
	for _, everyItem := range allFrequently {
		//标记汉语拼音和TAG标志
		if everyItem.RealName == "" {
			everyItem.Tag = "#"
			everyItem.NamePinyin = "#"
			continue
		}
		//标记汉语拼音
		for _, nameString := range pinyin.LazyConvert(everyItem.RealName, nil) {
			everyItem.NamePinyin += nameString
		}
		//标记汉语拼音首字母（大写）
		name := everyItem.NamePinyin
		if len(name) == 0 {
			everyItem.Tag = "#"
		} else if []byte(name)[0] >= 65 && []byte(name)[0] <= 90 || []byte(name)[0] >= 97 && []byte(name)[0] <= 122 {
			fmt.Println([]byte(name))
			everyItem.Tag = string([]byte(name)[0] - 32)
		} else {
			everyItem.Tag = "#"
		}
		everyItem.Added = 1
	}
	//排序
	sort.Sort(schema.CurrentPageItems(allFrequently))
	//掐取 指定的用户信息
	currentPageItems := make([]*schema.UserItemDetail, 0)
	if int(pageIndex)+int(pageSize)-1 <= len(allFrequently) {
		if pageIndex == 1 {
			currentPageItems = allFrequently[:pageIndex+pageSize]
		} else {
			currentPageItems = allFrequently[int(pageIndex) : pageIndex+pageSize]
		}
	} else {
		if pageIndex == 1 {
			currentPageItems = allFrequently[:]
		} else {
			currentPageItems = allFrequently[int(pageIndex):]
		}
	}
	resultArray := make([]*ArrayListUser, 0)
	if len(currentPageItems) == 0 {

	} else if len(currentPageItems) == 1 {
		itemMap := new(ArrayListUser)
		itemMap.Tag = currentPageItems[0].Tag
		itemMap.List = currentPageItems
		resultArray = append(resultArray, itemMap)
	} else {
		previousItem := new(ArrayListUser)
		previousItem.Tag = currentPageItems[0].Tag
		previousItem.List = make([]*schema.UserItemDetail, 0)
		previousItem.List = append(previousItem.List, currentPageItems[0])
		resultArray = append(resultArray, previousItem)
		for index := 1; index < len(currentPageItems); index++ {
			if currentPageItems[index].Tag == currentPageItems[index-1].Tag {
				previousItem.List = append(previousItem.List, currentPageItems[index])
			} else {
				previousItem = new(ArrayListUser)
				previousItem.Tag = currentPageItems[index].Tag
				previousItem.List = make([]*schema.UserItemDetail, 0)
				previousItem.List = append(previousItem.List, currentPageItems[index])
				resultArray = append(resultArray, previousItem)
			}
		}
	}
	return ctx.ResSuccess(resultArray)
}

// AddFrequentlyUsed 添加常用联系人
func (a *ContactsBook) AddFrequentlyUsed(ctx *context.Context) error {
	ctx.WriteOperateLog("ContactsBook.CreateFrequentlyUsed", "移动端-通讯录-添加常用联系人")
	var params schema.ContactsBookParams
	if err := ctx.ParseJSON(&params); err != nil {
		return ctx.ResErrBadRequest(err)
	}
	err := a.ContactsBookBll.AddFrequentlyUsed(ctx.GetUserID(), params.RecordID)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResOK()
}

// CancelFrequentlyUsed 取消常用联系人
func (a *ContactsBook) CancelFrequentlyUsed(ctx *context.Context) error {
	ctx.WriteOperateLog("ContactsBook.CancelFrequentlyUsed", "移动端-通讯录-取消常用联系人")
	userRecordID := ctx.Query("record_id")
	if userRecordID == "" {
		return ctx.ResErrBadRequest(nil)
	}

	err := a.ContactsBookBll.CancelFrequentlyUsed(ctx.GetUserID(), userRecordID)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResOK()
}
